/**
 * Created by Neville Kadwa.
 */

package org.shiftone.cdep.store;

import java.sql.DriverManager;
import java.sql.Connection;
import java.util.Properties;
import java.io.FileInputStream;

import org.apache.log4j.Logger;
import org.shiftone.cdep.store.StoreException;
import org.shiftone.cdep.store.StoreManager;

public class StoreManagerFactory
{

    public static final Logger LOG = Logger.getLogger(StoreManagerFactory.class);

    private static final String PROPERTIES = "cdep.properties";

    private static StoreManager storeManager = null;

    public static StoreManager getStoreManager() throws StoreException
    {
        if (storeManager == null)
        {
            LOG.debug("Starting Configuration");
            Properties props = new Properties();
            try
            {
                props.load(new FileInputStream(PROPERTIES));
            }
            catch (Exception ex)
            {
                throw new StoreException("Failed to load properties", ex);
            }

            String db = System.getProperty("db");
            if (db == null)
            {
                db = props.getProperty("default.db");
            }

            LOG.info("Loading [" + db + "] Database Configuration");

            try
            {
                Class.forName(props.getProperty(db + ".driver"));

                Connection connection = DriverManager.getConnection(props.getProperty(db + ".url"),
                                                                    props.getProperty(db + ".user"),
                                                                    props.getProperty(db + ".password"));
                connection.setAutoCommit(true);
                String managerClass = props.getProperty(db + ".manager");

                storeManager = (StoreManager) Class.forName(managerClass).newInstance();

                storeManager.setConnection(connection);
            }
            catch (Exception ex)
            {
                throw new StoreException("getStoreManager", ex);
            }
        }

        return storeManager;
    }

}

/* EOF */
